#include <stdlib.h>
#include "gogpc.h"

#define NUM_POLY 5

gpc_polygon gp[NUM_POLY];

gpc_vertex_list cb;
int cid;
int civ;


void init_poly (gpc_polygon * p); 
void free_poly (gpc_polygon * p);
void init_bound (gpc_vertex_list * cb); 
void free_bound (gpc_vertex_list * cb);

void init_poly (gpc_polygon * p) {
      p->num_contours = 0;
      p->hole = 0;
      p->contour = 0;
}

void free_poly (gpc_polygon * p) {
      gpc_free_polygon (p);
}

void init_bound (gpc_vertex_list * cb) {
      cb->vertex = 0;
      cb->num_vertices = 0;
}

void free_bound (gpc_vertex_list * cb) {
      cb->num_vertices = 0;
      free (cb->vertex);
      cb->vertex = 0;
}

void GPCInit ()
{
      int i;
      for (i = 0; i < NUM_POLY; ++ i) 
      {
            init_poly (gp + i);
      }
      init_bound (&cb);
}

void GPCFinalize ()
{
      int i;
      for (i = 0; i < NUM_POLY; ++ i)
      {
            free_poly (gp + i);
      }
      free_bound (&cb);
}

void SetNewPoly (int id) {
      gpc_free_polygon (gp + id); 
      cid = id;
}

void SetNewBound (int npoint)
{
      cb.num_vertices = npoint;
      cb.vertex = malloc (npoint * sizeof(gpc_vertex));
      civ = 0;
}

void SetNewPoint (double x, double y)
{
      cb.vertex[civ].x = x;
      cb.vertex[civ].y = y;
      ++ civ;
}

void SetEndBound ()
{
      gpc_add_contour (gp + cid, &cb, 0);
      free_bound(&cb);
}

void SetEndPoly ()
{
}

int   GetNBound (int id)
{
      return gp[id].num_contours;
}

char   GetIsHole (int id, int ibound)
{
      return gp[id].hole[ibound];
}

int    GetNPoint (int id, int ibound)
{
      return gp[id].contour[ibound].num_vertices;
}

double GetPointX (int id, int ibound, int iv)
{
      return gp[id].contour[ibound].vertex[iv].x;
}

double GetPointY (int id, int ibound, int iv)
{
      return gp[id].contour[ibound].vertex[iv].y;
}

void PolyDiff (int p1, int p2, int res)
{
      free_poly (gp + res);
      gpc_polygon_clip (GPC_DIFF, gp + p1, gp + p2, gp + res);
}

void PolyUnion (int p1, int p2, int res)
{
      free_poly (gp + res);
      gpc_polygon_clip (GPC_UNION, gp + p1, gp + p2, gp + res);
}

void PolyInter (int p1, int p2, int res)
{
      free_poly (gp + res);
      gpc_polygon_clip (GPC_INT, gp + p1, gp + p2, gp + res);
}
